package cn.ibizlab.util.service;

import cn.ibizlab.util.security.AuthenticationInfo;
import cn.ibizlab.util.security.AuthenticationUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Date;
import java.util.List;
import java.util.Map;

public abstract class AbstractAuthUserService implements AuthenticationUserService {

	@Autowired
	protected UserServiceAdapter userServiceAdapter;

	@Override
	@Cacheable( value="ibzuaa_users", key = "#root.target.systemId+':getByUsername:'+#p0")
	public AuthenticationUser loadUserByUsername(String username) {
		return createAuthenticationUser(userServiceAdapter.loadUserByUsername(username));
	}

	protected AuthenticationUser createAuthenticationUser(AuthenticationUser adapterUser) {
		return adapterUser;
	}

	@Override
	public AuthenticationInfo loadUserByLogin(String username, String password) {
		return userServiceAdapter.loadUserByLogin(username,password);
	}

	@Override
	@CacheEvict( value="ibzuaa_users", key = "'glob:*getByUsername:'+#p0")
	public void resetByUsername(String username) {

	}

	@Value("${ibiz.enablePermissionValid:false}")
	boolean enablePermissionValid;  //是否开启权限校验

	@Value("${ibiz.systemid}")
	private String systemId;

	public String getSystemId() {
		return this.systemId;
	}

	@Override
	public Map getAppData() {
		return userServiceAdapter.getAppData(systemId,enablePermissionValid);
	}

	@Override
	public Map<String, List<String>> getOrgInfo(String organizationId, String departmentId) {
		return userServiceAdapter.getOrgInfo(organizationId, departmentId);
	}

	@Override
	public String generateToken(UserDetails userDetails) {
		return userServiceAdapter.generateToken(userDetails);
	}

	@Override
	public Boolean validateToken(String token, UserDetails userDetails) {
		return userServiceAdapter.validateToken(token,userDetails);
	}

	@Override
	public String getUsernameFromToken(String token) {
		return userServiceAdapter.getUsernameFromToken(token);
	}

	@Override
	public Date getExpirationDateFromToken(String token) {
		return userServiceAdapter.getExpirationDateFromToken(token);
	}
}
